/*******************************************************************************
 * Package: com.practice.filter
 * Type:    JwtAuthorizationFilter
 * Date:    2023/9/27 16:48
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.practice.filter;

import com.alibaba.fastjson.JSON;
import com.practice.ex.ServiceErrorCode;
import com.practice.security.LoginUserInfo;
import com.practice.web.JsonResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 过滤器
 *
 * @author Masiyu
 * @date 2023/9/27 16:48
 */
@Component
@Slf4j
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    @Value("${practice.jwt.secret-key}")
    String secretKey;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 清除SecurityContext中的数据
        SecurityContextHolder.clearContext();
        
        String jwt = request.getHeader("jwt");
        log.debug("jwt：{}",jwt);
        if (!StringUtils.hasText(jwt) || jwt.length() < 113){
            filterChain.doFilter(request,response);
            return;
        }
    
        Claims claims = null;
        response.setContentType("application/json; charset=utf-8");
        try {
             claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (SignatureException e) {
            String message = "非法访问！";
            log.warn("解析JWT时出现SignatureException，响应消息：{}", message);
            JsonResult jsonResult = new JsonResult(ServiceErrorCode.ERR_BAD_REQUEST.getCode(), message);
            PrintWriter printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(jsonResult));
            printWriter.close();
            return;
        } catch (MalformedJwtException e) {
            String message = "非法访问！";
            log.warn("解析JWT时出现MalformedJwtException，响应消息：{}", message);
            JsonResult jsonResult = new JsonResult(ServiceErrorCode.ERR_BAD_REQUEST.getCode(), message);
            PrintWriter printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(jsonResult));
            printWriter.close();
            return;
        } catch (ExpiredJwtException e) {
            String message = "您的登录信息已过期，请重新登录！";
            log.warn("解析JWT时出现ExpiredJwtException，响应消息：{}", message);
            JsonResult jsonResult = new JsonResult(ServiceErrorCode.ERR_BAD_REQUEST.getCode(), message);
            PrintWriter printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(jsonResult));
            printWriter.close();
            return;
        }
        Long id = claims.get("id",Long.class);
        String name = claims.get("name",String.class);
        String state = claims.get("state",String.class);
        log.debug("jwt解析出的id:{}",id);
        log.debug("jwt解析出的name:{}",name);
    
        // 基于解析JWT的结果创建认证信息
        LoginUserInfo userInfo = new LoginUserInfo();
        userInfo.setId(id);
        userInfo.setName(name);
        userInfo.setState(state);
        
        // 权限↓ 暂时不用
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("暂时给个山寨的权限");
//        authorities.add(simpleGrantedAuthority);
        
        // 将认证信息存入到SecurityContext中
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userInfo,null,null));
        //放行
        filterChain.doFilter(request,response);
    }
}
